<template>
  <div class="pie-chart">
    <div class="pie-echart__content" ref="echartRef"></div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted } from 'vue'

const props = defineProps({
  title: {
    type: String || Object,
    default: ''
  },
  cols: {
    type: Array,
    default: () => {
      return []
    }
  },
  datas: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const echartRef = ref()

watch(() => props.cols, draw)
watch(() => props.datas, draw)

function draw() {
  let titleConfig = undefined
  switch (typeof props.title) {
    case 'string':
      titleConfig = {
        text: props.title,
        subtext: '',
        left: 'center',
        // right: 0,
        bottom: 0,
        textStyle: {
          color: 'aqua',
          // color: '#35a3b6',
          fontWeight: 'normal',
          fontSize: 22,
          fontFamily: 'serif'
        }
      }
      break
    case 'object':
      titleConfig = props.title
      break
  }
  let list = props.cols.map((r) => {
    const { title, property } = r
    const val = props.datas[property] || 0
    return { name: title, value: val }
  })
  let option = {
    title: titleConfig,
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['45%', '70%'],
        avoidLabelOverlap: false,
        // padAngle: 1,
        // itemStyle: {
        //   borderRadius: 10
        // },
        // top: -30,
        label: {
          show: true,
          position: 'outside', // center
          formatter: '{b} {c}\n占比 {d}%',
          fontSize: 12,
          lineHeight: 20,
          color: '#FFF'
          // fontFamily: 'sans-serif'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 22,
            lineHeight: 30,
            fontWeight: 'normal'
          }
        },
        labelLine: {
          show: true,
          showAbove: true,
          length: 20,
          lineStyle: {
            color: '#FFF'
            // type: 'dashed'
          }
        },
        data: list,
        color: ['#00BFFF', '#FF4500']
      }
    ]
  }

  let myChart = echarts.init(echartRef.value, 'light', { renderer: 'canvas', useDirtyRect: false })
  myChart.setOption(option)
  setTimeout(myChart.resize, 300)
}

onMounted(() => {
  draw()
})
</script>
<style lang="less" scoped>
.pie-chart {
  width: 100%;
  height: 100%;
  ::v-deep(.pie-echart__content) {
    width: 100%;
    height: 100%;
    position: relative;
    > div {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>
